#!/bin/bash
set -e
set -x

ROOT_DIR='../dist/web'

pub() {
    rm -rf $ROOT_DIR
    mkdir -p $ROOT_DIR
    pnpm run build
    cp -rf ./dist $ROOT_DIR
}

img() {

    echo ' 
user  nginx;
worker_processes  1;
error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;
events {
  worker_connections  1024;
}
http {
  include       /etc/nginx/mime.types;
  default_type  application/octet-stream;
  log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                    '$status $body_bytes_sent "$http_referer" '
                    '"$http_user_agent" "$http_x_forwarded_for"';
  access_log  /var/log/nginx/access.log  main;
  sendfile        on;
  keepalive_timeout  65;
  server {
    listen       80;
    server_name  localhost;
    location / {
        root /app;   
        index  index.html;
        try_files $uri $uri/ /index.html;    
    }

    location /api {
        proxy_set_header Host $http_host;
        proxy_set_header  X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        rewrite ^/api/(.*)$ /$1 break;
        proxy_pass http://192.168.31.205:9000;
    }
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
      root   /usr/share/nginx/html;
    }
  }
}
' >"${ROOT_DIR}/nginx.conf"

    echo '
FROM nginx:alpine
RUN apk add --no-cache tzdata
ENV TZ Asia/Shanghai
ENV ADMIN 192.168.31.205
COPY ./nginx.conf /etc/nginx/nginx.conf
COPY ./dist /app

EXPOSE 80
' >"${ROOT_DIR}/dockerfile"

    echo '
Dockerfile
' >"${ROOT_DIR}/.dockerignore"

    IMAGE="registry.cn-shenzhen.aliyuncs.com/1461076997/web:latest"
    cd $ROOT_DIR && pwd && docker build --platform=linux/arm/v7 -t $IMAGE .
    docker push $IMAGE
}

a() {
    pub
    img
}

$@
